package org.ethereum.sync;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.ethereum.config.SystemProperties;

/**
 * for the purpose of speed-up the launching process.
 * 
 * @author shaolinwu
 *
 */
public class CopyPeerDBDownloader {

	public void copy() {
		File file = new File(SystemProperties.getDefault().databaseDir(), "blockchain");
		// copy this directory to a backup at first.
		copyFile(file, new File(SystemProperties.getDefault().databaseDir(), "blockchainbackup"));
		// TODO: send it to destination server.
	}

	public static void copyFile(File file, File file2) {
		if (file.isDirectory()) {
			file2.mkdir();
			File[] files = file.listFiles();
			for (File file3 : files) {
				copyFile(file3, new File(file2, file3.getName()));
			}
		} else if (file.isFile()) {
			File file3 = new File(file2.getAbsolutePath());
			try {
				file3.createNewFile();
				copyDatas(file.getAbsolutePath(), file3.getAbsolutePath());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void copyDatas(String filePath, String filePath1) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(filePath);
			fos = new FileOutputStream(filePath1);
			byte[] buffer = new byte[1024];
			while (true) {
				int temp = fis.read(buffer, 0, buffer.length);
				if (temp == -1) {
					break;
				} else {
					fos.write(buffer, 0, temp);
				}
			}
		} catch (IOException e) {
			System.out.println(e);
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				System.out.println(e);
			}
		}
	}
}
